package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.adapter.FindSearchAdapter;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.LogUtil;
import striveen.util.used.view.view.XListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 16/2/23.
 * 发现搜索页面
 */
public class FindSearchActivity extends BaseActivity {
    /**
     * 搜索框的隐藏与显示
     */
    @ViewInject(id = R.id.linearlayout_search)
    private LinearLayout linearlayout_search;
    /**
     * 搜索商品
     */
    @ViewInject(id = R.id.search_ed)
    private EditText search_ed;
    @ViewInject(id = R.id.do_search_iv, click = "do_search_iv_click")
    private ImageView do_search_iv;

    /**
     * 清楚搜索内容
     */
    @ViewInject(id = R.id.clear_search_iv, click = "clear_search_iv_click")
    private ImageView clear_search_iv;

    /**
     * 搜索取消
     */
    @ViewInject(id = R.id.tv_search_cancel, click = "tv_search_cancel_click")
    private TextView tv_search_cancel;

    @ViewInject(id = R.id.xListView)
    private XListView xListView;
    private FindSearchAdapter findSearchAdapter;
    /**
     * 无相关数据
     */
    @ViewInject(id = R.id.nodata_layout, click = "nodata_layout_click")
    private LinearLayout nodata_layout;

    private int nPage = 0;
    private ArrayList<JsonMap<String, Object>> dataList = new ArrayList<JsonMap<String, Object>>();
    private String key = "";   //搜索框中的字

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_search_layout);
        linearlayout_search.setVisibility(View.VISIBLE);
        xListView.setVisibility(View.GONE);
        findSearchAdapter = new FindSearchAdapter(mContext, dataList);
        xListView.setAdapter(findSearchAdapter);

        xListView.setPullRefreshEnable(true);
        xListView.setPullLoadEnable(true);
        xListView.setXListViewListener(loadMoreListener);
        xListView.setOnItemClickListener(onItemClickListener);
//        xListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                LogUtil.d(TAG,"position"+position);
//            }
//        });
        search_ed.setOnEditorActionListener(editorActionListener);
    }

    private TextView.OnEditorActionListener editorActionListener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                key = search_ed.getText().toString();
                if (TextUtils.isEmpty(key)) {
                    toast.showToast(R.string.search_key_null);
                    return true;
                } else {
                    loadingToast.show();
                    nPage = 0;
                    getSearchData();
                    return true;
                }
            }
            return false;
        }
    };

    /**
     * item  点击监听
     */
    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int itemPosition, long id) {
            JsonMap jsonMap_temp = dataList.get(itemPosition - 1);
            String discoreId = jsonMap_temp.getStringNoNull("Id");
            Intent intent = new Intent(mContext, FindDetailActivity.class);
            intent.putExtra(Constant.ID, discoreId);
            intent.putExtra(Constant.NAME, jsonMap_temp.getStringNoNull("Title"));
            jumpTo(intent, false);
        }
    };

    private XListView.IXListViewListener loadMoreListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            nPage = 0;
            getSearchData();
        }

        @Override
        public void onLoadMore() {
            getSearchData();
        }
    };

    /**
     * 开始搜索
     */
    private void getSearchData() {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("currentPage", nPage + 1);
        params.put("Title", key);
        params.put("pageSize", 10);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscover);

        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetDiscover);
        getDataUtil.getData(queue);
    }


    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            xListView.stopLoadMore();
            xListView.stopRefresh();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetDiscover) {
                        List<JsonMap<String, Object>> temp_data = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setAdapterData(temp_data);
                        validateData();
                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
        }

    };

    /**
     * 校验数据 显示无数据等
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param
     */
    private void validateData() {

        if (dataList == null || dataList.size() == 0) {
            xListView.setVisibility(View.GONE);
            nodata_layout.setVisibility(View.VISIBLE);
        } else {
            xListView.setVisibility(View.VISIBLE);
            nodata_layout.setVisibility(View.GONE);
        }

    }

    private void setAdapterData(List<JsonMap<String, Object>> temp_data) {
        if (temp_data.size() == 0) {
            xListView.setPullLoadEnable(false);
        } else {
            xListView.setPullLoadEnable(true);
        }
        if (nPage == 0) {
            dataList.clear();
        }
        findSearchAdapter.setSpecialStr(key);
        dataList.addAll(temp_data);
        findSearchAdapter.setDatas(dataList);
        findSearchAdapter.notifyDataSetChanged();

        nPage++;
    }

    public void clear_search_iv_click(View view) {
        search_ed.setText("");
    }

    /**
     * 搜索
     *
     * @param view
     */
    public void do_search_iv_click(View view) {
        key = search_ed.getText().toString();
        if (TextUtils.isEmpty(key)) {
            toast.showToast(R.string.search_key_null);
        } else {
            loadingToast.show();
            nPage = 0;
            getSearchData();
        }
    }

    /**
     * 取消搜索
     */
    public void tv_search_cancel_click(View view) {
        finish();
    }
}